package main

import (
    "flag"
    "fmt"
    "log"
    "time"

    "goserver/tools/loganalyzer"
    "goserver/tools/profiler"
)

var (
    logFile     = flag.String("log", "logs/app.log", "日志文件路径")
    cpuProfile  = flag.String("cpu", "cpu.pprof", "CPU性能分析文件")
    memProfile  = flag.String("mem", "mem.pprof", "内存性能分析文件")
    duration    = flag.Duration("duration", 30*time.Second, "性能分析持续时间")
    serverAddr  = flag.String("server", "localhost:8080", "服务器地址")
)

func main() {
    flag.Parse()

    // 1. 启动性能分析
    prof, err := profiler.NewProfiler(
        profiler.WithCPUProfile(*cpuProfile),
        profiler.WithMemProfile(*memProfile),
        profiler.WithGoroutineProfile(),
        profiler.WithBlockProfile(),
    )
    if err != nil {
        log.Fatalf("创建性能分析器失败: %v", err)
    }

    prof.Start()
    defer prof.Stop()

    // 2. 分析日志
    analyzer := loganalyzer.NewLogAnalyzer()

    // 添加常用日志模式
    patterns := map[string]string{
        "timestamp": `time="([^"]+)"`,
        "level":     `level=(\w+)`,
        "msg":       `msg="([^"]+)"`,
        "path":      `path="([^"]+)"`,
        "method":    `method=(\w+)`,
        "status":    `status=(\d+)`,
        "latency":   `latency=([0-9.]+[µmsh]+)`,
        "ip":        `ip=([0-9.]+)`,
    }

    for name, pattern := range patterns {
        if err := analyzer.AddPattern(name, pattern); err != nil {
            log.Printf("添加模式 %s 失败: %v", name, err)
        }
    }

    // 分析日志文件
    if err := analyzer.ParseFile(*logFile); err != nil {
        log.Printf("分析日志文件失败: %v", err)
    }

    // 生成分析报告
    result := analyzer.Analyze()
    report := result.GenerateReport()

    // 输出报告
    fmt.Println("\n=== 性能分析报告 ===")
    fmt.Printf("分析时间: %s\n", time.Now().Format("2006-01-02 15:04:05"))
    fmt.Printf("服务器地址: %s\n", *serverAddr)
    fmt.Printf("日志文件: %s\n", *logFile)
    fmt.Printf("CPU分析文件: %s\n", *cpuProfile)
    fmt.Printf("内存分析文件: %s\n", *memProfile)
    fmt.Printf("\n%s", report)
} 